import { NestInterceptor, ExecutionContext } from "@nestjs/common";
import { Observable } from "rxjs";
import {map } from 'rxjs/operators'
import * as util from 'util'
import { View } from "../libs/View";

export class ViewInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
    // 获取response对象
    const response = context.switchToHttp().getResponse()

    // 将 render 回调函数转为一个 promisify 饭后绑定执行的上下文
    const render = util.promisify(response.render.bind(response))

    return call$.pipe(map(async value => {

      if (value instanceof View) {
        // 返回渲染后的 html
        value = await render(value.name, value.data);

      }

      return value;

    }))

  }
}

// https://www.jianshu.com/p/3a09dce67a33